package com.albert.websocketsimple;

import java.security.Principal;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WsController {

	@Autowired
	private MyWebSocketHandler myWebSocketHandler;

	// 访问跳转到websocket.html页面
	@RequestMapping("/socket")
	public String websocket() {
		return "websocket";
	}

	// 模拟登陆操作，将用户信息存入Session
	@RequestMapping("/login")
	@ResponseBody
	public void login(@RequestParam String userId, HttpServletRequest request) {

		request.getSession().setAttribute("user", userId);
	}

	// 普通操作，触发WebSocket通信
	@RequestMapping("/send/message")
	@ResponseBody
	public String sendMessage(HttpServletRequest request ,@RequestParam String to,@RequestParam String msg) {
		String userId = (String) request.getSession().getAttribute("user");
		//boolean isSuccess = myWebSocketHandler.sendMessageToUser(userId, "测试发送消息");
		boolean isSuccess = myWebSocketHandler.sendMessageToUser(to, msg);
		System.out.println(isSuccess);
		return "message";
	}
}